﻿var $edittr;
var ServiceId = GetQueryString("Id");
var dataSourceId = GetQueryString("dataSourceId");
$(function () {
    $("#DataServiceId").val(ServiceId);
    GetCodeDataTypeSelectList();//初始化下拉框数据
    getServiceDetails();//获取服务详细信息
    if (dataSourceId != "") {
        $(".sub_Title").html("编辑数据源-Excel");
        $("#hidden_input").append("<input type=\"hidden\" name=\"DataSourceId\" id=\"DataSourceId\" value=\"" + dataSourceId + "\"/>");
        getDataSourceDetails();
        //$("#SourceName").attr("disabled", "disabled");
        $("#FirstRowAsHeader").attr("disabled", "disabled");
        $("#ServiceName").attr("disabled", "disabled");
    }

    //给文件域赋值
    $("#Template").change(function () {
        var $this = $(this);
        $this.parent().next().val($this.val());
    });
    //ajax上传文件
    $("#upload-btn").click(function () {
        $("#Template").upload({
            // 上传地址
            action: apiUrl,
            // 文件域名字
            name: 'Template',
            // 其他表单数据
            data: { 'sys:sno': "Excel", "sys:act": "UploadTemplate", "FirstRowIsHeader": $("#FirstRowAsHeader").val() },
            // 上传完成后, 返回json, text
            // dataType: 'json',
            // 上传之后回调
            onsuccess: function (data) {
                if (data.IsSccuess) {
                    AppadData(data.Data.Items);
                } else {
                    if (IsLogined(data.ErrorCode)) {
                        alert("上传失败（" + "错误代码：" + data.ErrorCode + "，错误信息：" + data.Message + ")");
                    }
                }
            },onerror: function() {
                alert("系统异常，请稍后再试！");
            }
        });
    });
    //新增的操作
    $("#add-type-form").validate({
        submitHandler: function () {
            try {
                var obj = {};
                obj.name = $("#add-type-Name").val();
                obj.colum = $("#add-type-Column").val();
                obj.type = $("#add-type-DataTypeSelect").val();
                obj.description = $("#add-type-Description").val().replace(",", "，");
                var state = true;
                var list = $("#table-details tbody tr");
                if (list != undefined) {
                    for (var j = 0; j < list.length; j++) {
                        var tempjson = JSON.parse($(list[j]).attr("data"));
                        if (obj.name.toUpperCase() == tempjson.name.toUpperCase()) {
                            state = false;
                            break;
                        } else if (tempjson.colum.toUpperCase() == obj.colum.toUpperCase()) {
                            state = false;
                            break;
                        }
                    }
                }
                if (state) {
                    var tr = AssembleData(obj);
                    $("#table-details").append(tr);
                    ShowGritter("添加成功");
                    $('#add-type-modal').modal('hide');
                } else {
                    ShowGritter("excel列或列已存在");
                }
            } catch (e) {
                console.log(e);
            }
        }
    });
    //编辑的操作
    $("#update-type-form").validate({
        submitHandler: function () {
            try {
                var obj = {};
                obj.name = $("#update-type-Name").val();
                obj.colum = $("#update-type-Column").val();
                obj.type = $("#update-type-DataTypeSelect").val();
                obj.description = $("#update-type-Description").val().replace(",", "，");
                if ($edittr != null) {
                    var list = $("#table-details tbody tr");
                    var state = true;
                    var objjson = JSON.parse($edittr.attr("data"));
                    if ((obj.name.toUpperCase() == objjson.name.toUpperCase()) && (obj.colum.toUpperCase() == objjson.colum.toUpperCase())) {
                        state = true;
                    }
                    else if (obj.name.toUpperCase() == objjson.name.toUpperCase()) {
                        state = AuditData("", obj.colum, list);
                    } else if (obj.colum.toUpperCase() == objjson.colum.toUpperCase()) {
                        state = AuditData(obj.name, "", list);
                    } else {
                        state = AuditData(obj.name, obj.colum, list);
                    }
                    if (state) {
                        $(AssembleData(obj)).replaceAll($edittr);
                        ShowGritter("编辑成功");
                        $('#update-type-modal').modal('hide');
                    } else {
                        ShowGritter("列已存在");
                    }

                } else {
                    alert("编辑对象不存在");
                }

            } catch (e) {
                console.log(e);
            }
        }
    });
    $("#AddDataSource").validate({
        submitHandler: function () {
            try {
                var trlist = $("#table-details tbody tr");
                if (trlist.length > 0) {
                    var str = "";
                    for (var i = 0; i < trlist.length; i++) {
                        var tempjson = JSON.parse($(trlist[i]).attr("data"));
                        str += (tempjson.name + ":" + tempjson.colum + ",");
                        str += (tempjson.type + ",");
                        str += (tempjson.description);
                        if (i != (trlist.length - 1)) {
                            str += ",";
                        }
                    }
                    console.log(str);
                    $("#ColumnSettings").val(str);
                    //修改   
                    var url = "DataSourceDetails-Excel.html?Id=" + ServiceId;
                    if (dataSourceId != "") {
                        $.ajax({
                            url: g_webApiBaseUrl + 'Update/DtSrcCols',
                            type: "Post",
                            dataType: "json",
                            data: {
                                "dtSerId": ServiceId,
                                "dtSrcId": dataSourceId,
                                dtSrcName: $("#SourceName").val(),
                                "cols": str
                            },
                            success: function (data) {
                                if (data.IsSuccess) {
                                    ShowGritter("保存成功", 2, url);
                                } else {
                                    if (IsLogined(data.ErrorCode)) {
                                        alert("修改失败（" + "错误代码：" + data.ErrorCode + "，错误信息：" + data.Message + ")");
                                    }
                                }
                            },
                            beforeSend: function () {
                                ShowGritter("提交中");
                            }
                        });
                    } else {//新增
                        $.ajax({
                            url: apiUrl,
                            type: "Post",
                            dataType: "json",
                            data: $("#AddDataSource").serialize(),
                            success: function (data) {
                                if (data.IsSccuess) {
                                    ShowGritter("保存成功", 2, url);
                                } else {
                                    if (IsLogined(data.ErrorCode)) {
                                        alert("新增失败（" + "错误代码：" + data.ErrorCode + "，错误信息：" + data.Message + ")");
                                    }
                                }
                            },
                            beforeSend: function () {
                                ShowGritter("提交中");
                            }
                        });
                    }
                } else {

                    alert("参数列表为空，不允许提交");
                }
            } catch (e) {
                console.log(e);
            }

        }
    });
});
//组合数据
var AppadData = function (data) {
    var trlist = "";
    var list = $("#table-details tbody tr");
    for (var i = 0; i < data.length; i++) {
        var $this = data[i];
        var str = $this.Name.split(':');
        var name = str[0];
        var colum = str[1];
        var state = AuditData(name, colum, list);
        if (state) {
            trlist += AssembleData({ name: name, colum: colum, type: $this.Type, description: ($this.Description == undefined ? "" : $this.Description) });
        }
    }
    $("#table-details tbody").append(trlist);
}
//传入data对象返回一行的表格数据
var AssembleData = function (data) {
    var tr = "<tr data='" + JSON.stringify(data) + "'><td>";
    tr += (data.name + "</td>");
    tr += ("<td>" + data.colum + "</td>");
    tr += ("<td>" + data.type + "</td>");
    tr += ("<td>" + data.description + "</td>");//备注
    tr += ("<td>  <a href='javascript:void(0)' onclick=\"UpateData(this)\"><i class='fa fa-pencil-square-o '></i>编辑</a>&nbsp;<a href='javascript:void(0)' onclick=\"DeleteData(this)\"><i class='fa  fa-times-circle'></i>删除</a></td></tr>");
    return tr;

}
//删除当前行数据
var DeleteData = function (obj) {
    if (confirm("是否删除？")) {
        $(obj).parent().parent().remove();
    }
}
//获取可用代码的select列表
var GetCodeDataTypeSelectList = function () {
    var list = GetCodeDataType();
    var str = "";
    for (var i = 0; i < list.length; i++) {
        str += ("<option value=\"" + list[i] + "\">" + list[i] + "</option>");
    }
    $("#add-type-DataTypeSelect").append(str);
    $("#update-type-DataTypeSelect").append(str);
}
//获取服务的详细信息
var getServiceDetails = function () {
    $.ajax({
        url: apiUrl,
        data: {
            "sys:sno": "Excel",
            "sys:act": "GetDataService",
            "ServiceId": ServiceId
        },
        dataType: "json",
        success: function (data) {
            if (data.IsSccuess) {
                $("#ServiceName").val(data.Data.Name);
            } else {
                if (IsLogined(data.ErrorCode)) {
                    alert(data.Message);
                }
            }
        },
        beforeSend: function () {
            // $("btn_login").html("登录中...");
        }
    });
}
var getDataSourceDetails = function () {
    $.ajax({
        url: apiUrl,
        data: {
            "sys:sno": "ETL",
            "sys:act": "GetDataSource",
            "DataServiceId": ServiceId,
            "DataSourceId": dataSourceId
        },
        dataType: "json",
        success: function (data) {
            if (data.IsSccuess) {
                var str = "";
                $("#SourceName").val(data.Data.Name);//名称
                if (data.Data.FirstRowAsHeader != undefined) {
                    $("#FirstRowAsHeader").val(data.Data.FirstRowAsHeader);
                }

                AppadData(data.Data.Columns);//组装数据并并填充表格
            } else {
                if (IsLogined(data.ErrorCode)) {
                    alert(data.Message);
                }
            }
        },
        beforeSend: function () {
            // $("btn_login").html("登录中...");
        }
    });
}

//编辑按钮触发的操作
var UpateData = function (obj) {
    $edittr = $(obj).parent().parent();
    var json = $edittr.attr("data");
    var jsonobj = JSON.parse(json);
    $("#update-type-Name").val(jsonobj.name);
    $("#update-type-Column").val(jsonobj.colum);
    $("#update-type-DataTypeSelect").val(jsonobj.type);
    $("#update-type-Description").val(jsonobj.description);
    $('#update-type-modal').modal({
        show: true
    });
}
//新增按钮触发的操作
var AddData = function () {
    document.getElementById('add-type-form').reset();
    $('#add-type-modal').modal({
        show: true
    });
}
var AuditData = function (name, column, list) {
    var state = true;
    if (list != undefined) {
        for (var j = 0; j < list.length; j++) {
            var tempjson = JSON.parse($(list[j]).attr("data"));
            if (name.toUpperCase() == tempjson.name.toUpperCase()) {
                state = false;
                break;
            } else if (tempjson.colum.toUpperCase() == column.toUpperCase()) {
                state = false;
                break;
            }
        }
    }
    return state;
}